package ilbunilcho.lol.parser;

import ilbunilcho.lol.exception.ChampionNotFoundException;
import ilbunilcho.lol.exception.ServerUnavailableException;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ChampionRotation {
	String url = null;
	String[] ret = null;
	
	public ChampionRotation(String baseUrl) {
		this.url = baseUrl + "/news/champion-rotation";
	}
	
	public void parse() throws ServerUnavailableException, ChampionNotFoundException {
		try {
			Document doc = Jsoup.connect(url).get();
			Element body = doc.body();
			
			Elements rotations = body.select("div#content_area div#region_content div.view-content div.views-row-1 div.article_body a[href^=http]");
			if(!rotations.isEmpty()) {
				Iterator<Element> iter = rotations.iterator();
				
				File f = null;
				int cnt = 0;
				ret = new String[rotations.size()];
				while(iter.hasNext()) {
					Element el = iter.next();
					
					String src = el.child(0).attr("src");
					f = new File(src);
					
					if(f != null) {
						ret[cnt] = f.getName().replace(".jpg", "");
					}

					f = null;
					cnt++;
				}
			}
			else {
				throw new ChampionNotFoundException();
			}
		}
		catch(IOException e) {
			throw new ServerUnavailableException();
		}
	}
	
	public String[] getRotation() {
		return ret;
	}
}
